package main

import "net"
import (
	"fmt"
	"bufio"
	"time"
)

func leaveRoom(conn *net.TCPConn,idstr string,w *bufio.Writer){
	time.Sleep(20*time.Second)
	pp := &Proto{Ver:1,Cmd:LEAVE_ROOM}
	pp.SetHeader([]byte(idstr))
	pp.SetData([]byte("room"))
	if _,err := pp.WriteTcp(w);err != nil{
		conn.Close()
		return
	}
}

func sendHeart(conn *net.TCPConn,idstr string,w *bufio.Writer){
	for {
		time.Sleep(5 * time.Second)
		pp := &Proto{Ver: 1, Cmd: HEARTBEAT}
		pp.SetHeader([]byte(idstr))
		pp.SetData([]byte("HEARTBEAT"))
		if _, err := pp.WriteTcp(w); err != nil {
			conn.Close()
			return
		}
	}
}


func beginClient(addr string,id int){
	tcpAddr, err := net.ResolveTCPAddr("tcp4", addr)
	if err != nil{
		fmt.Println("ResolveTCPAddr error =>",err)
	}
	conn, derr := net.DialTCP("tcp", nil, tcpAddr)

	if derr != nil{
		fmt.Println("DialTCP error =>",derr)
		return
	}

	r := bufio.NewReader(conn)
	w := bufio.NewWriter(conn)

	idstr := fmt.Sprintf("user %d",id)
	p := &Proto{Ver:1,Cmd:AUTH}
	p.SetHeader([]byte(idstr))
	p.SetData([]byte("xxxuser"))

	if _,err := p.WriteTcp(w);err != nil{
		conn.Close()
		return
	}

	//if id % 24 != 0{

	//}


	for{
		reply := &Proto{}
		_,perr := reply.ReadTcp(r)
		if perr != nil {
			conn.Close()
			break
		}
		if reply.Cmd == AUTH_REPLY{
			if id%200 == 0{
				pp := &Proto{Ver:1,Cmd:JOIN_ROOM}
				pp.SetHeader(reply.Data)
				pp.SetData([]byte("room3"))
				if _,err := pp.WriteTcp(w);err != nil{
					conn.Close()
					return
				}
			}
			if id %400 == 0{
				go leaveRoom(conn,string(reply.Data),w)
			}
			go sendHeart(conn,string(reply.Data),w)
		}
		if reply.Cmd != HEARTBEAT_REPLY{
			fmt.Println(id,"reply:",string(reply.Data))
		}

	}


}
func testGo(){
	for{
		time.Sleep(10*time.Second)
	}
}
func main() {

	addr :="192.168.1.105:8133"
	for i:= 2002;i <= 4000;i++{
		go beginClient(addr,i)
		//go testGo()
		if i%200 == 0{
			time.Sleep(100*time.Millisecond)
			fmt.Println("===========================count :",i)
		}
	}
	for{
		time.Sleep(10*time.Second)
	}


}
